package com.guosen.zebra.framework.starter.ngx.internal.impl;



import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.guosen.zebra.framework.starter.ngx.exception.NgxException;
import com.guosen.zebra.framework.starter.ngx.model.InvokeContext;
import com.guosen.zebra.framework.starter.ngx.model.MoveParameter;
import com.guosen.zebra.framework.starter.ngx.model.MoveResult;
import com.guosen.zebra.framework.starter.ngx.util.UrlEncodeDecoder;

import java.util.HashMap;
import java.util.Map;

public class UniNgxMove {

    private static final String MOVE_PATH = "/UniExServices/restfulapi/%s%s";

    public MoveResult execute(MoveParameter moveParameter, InvokeContext invokeContext) throws NgxException {
        String urlEncodeAccount = UrlEncodeDecoder.encode(invokeContext.getAccount());
        String urlEncodePath = UniNgxUtil.urlEncodePath(moveParameter.getPath());
        String urlPath = String.format(MOVE_PATH, urlEncodeAccount, urlEncodePath);

        String url = invokeContext.getAddress() + urlPath;

        Map<String, String> headers = UniNgxUtil.buildHeaders(invokeContext);
        Map<String, String> parameters = buildParameter(moveParameter);

        JsonNode result = UniNgxRestfulClient.get(url, headers, parameters);
        UniNgxUtil.raiseExceptionIfExist(result);

        try {
            return UniNgxUtil.getObjectMapper().treeToValue(result, MoveResult.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    private Map<String, String> buildParameter(MoveParameter moveParameter) {
        Map<String, String> parameters = new HashMap<>();
        UniNgxUtil.addParameter(parameters, "method", "move");
        UniNgxUtil.addParameter(parameters, "from", moveParameter.getFrom());
        UniNgxUtil.addParameter(parameters, "is_dir", moveParameter.getIsDir());

        return parameters;
    }
}
